package com.house.internal.service;

import java.util.List;
import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.house.core.dao.EmployeesDao;
import com.house.core.model.Employees;
import com.house.core.model.ErrorCode;
import com.house.core.model.response.LoginResponse;
import com.house.core.model.response.RegisterResponse;
import com.house.core.model.response.ValidateUsernameResponse;
import com.house.core.service.EmployeesService;
import com.house.core.util.MD5Util;

/**
 *
 *
 * @author <a href="mailto:chong.sun@renren-inc.com">sun chong</a>
 * @version 2013-2-22
 */
@Service
public class EmployeesServiceImpl implements EmployeesService {
	
	@Resource(type = EmployeesDao.class)
	private EmployeesDao employeesDao;
	
	@Override
	public LoginResponse login(Long jobNumber, String username, String password) {
		Employees employees = null;
		if(jobNumber != null){
			employees = employeesDao.getEmployeesByUid(jobNumber);
		}else{
			employees = employeesDao.getEmployeesByUsername(username);
		}
		LoginResponse resp = new LoginResponse();
		if(employees == null){
			//用户不存在，进行处理
			resp.setErrorCode(ErrorCode.USERNAME_NOT_EXIST);
			return resp;
		}
		if(!employees.getPassword().equals(MD5Util.md5(password))){
			//密码错误，进行处理
			resp.setErrorCode(ErrorCode.USERNAME_PASSWORD_NOT_MATCH);
			return resp;
		}
		resp.setEmployees(employees);
		return resp;
	}

	@Override
	public RegisterResponse register(Employees employees) {
		RegisterResponse resp = new RegisterResponse();
		long id = employeesDao.addEmployees(employees);
		resp.setJobNumber(id);
		return resp;
	}

	@Override
	public ValidateUsernameResponse validateUsername(String username) {
		ValidateUsernameResponse resp = new ValidateUsernameResponse();
		if(employeesDao.getEmployeesByUsername(username) == null){
			return resp;
		}
		resp.setErrorCode(ErrorCode.USERNAME_REPEAT);
		List<Employees> employeesList =  employeesDao.getEmployeesLikeUsername(username);
		String lastUsername = employeesList.get(employeesList.size() - 1).getUsername();
		String suffix = lastUsername.replace(username, "");
		int no = StringUtils.isBlank(suffix) ? 0 : Integer.parseInt(suffix);
		resp.setRecommendNum(++no);
		return resp;
	}
}
